import { reqGetCode } from "@/api";
import { reqRegister } from "@/api";
import { reqLogin } from "@/api";
import { reqGetUserInfo } from "@/api";
import { reqLogout } from "@/api";

let state = {
    //验证码
    code: '',
    token: localStorage.getItem('token'),
    userInfo: {}
};

let mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    LOGIN(state, token) {
        state.token = token;
    },
    GETUSERINFO(state, data) {
        state.userInfo = data;
    },
    LOGOUT(state) {
        localStorage.removeItem('token');
        state.token = "";
        state.userInfo = {};
    }
};

let actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone);
        console.log(result);
        if (result.code == 200) {
            commit('GETCODE', result.data);
            return "ok"
        } else {
            return Promise.reject();
        }
    },
    /* eslint-disable */
    //请求注册
    async register({ commit }, data) {
        let result = await reqRegister(data);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject();
        }
    },
    /* eslint-disable */
    //登录
    async login({ commit }, data) {
        let result = await reqLogin(data);
        console.log(result);
        if (result.code == 200) {
            commit("LOGIN", result.data.token);
            localStorage.setItem('token', result.data.token);
            return 'ok'
        } else {
            return Promise.reject();
        }
    },
    //获取用户登录信息
    async getUserInfo({ commit }) {
        let result = await reqGetUserInfo();
        if (result.code == 200) {
            commit("GETUSERINFO", result.data);
            return 'ok';
        } else {
            return Promise.reject();
        }
    },
    //退出登录
    async logout({ commit }) {
        let result = await reqLogout();
        if (result.code == 200) {
            commit('LOGOUT');
            return "ok"
        } else {
            return Promise.reject();
        }
    }
};

let getters = {};

export default {
    state,
    mutations,
    actions,
    getters
}